<template>
<!-- 微信群机器人 -->
  <!-- 搜索工作栏 -->
   <div v-show="setView==='list'">
  

      <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams">
      </Search>

    <!-- 列表 -->
      <div style="margin: 10px 0;">
        <el-button
            type="primary"
            @click="openForm('create','')"
            v-hasPermi="['pictureTemplate:saveOrUpdate']"
          >
            新增
          </el-button>
          
          <el-button
            type="primary"
            @click="handleDownDoad"
          >
            下载
          </el-button>
          <el-button
            type="primary"
            @click="handleTest"
            v-hasPermi="['pictureRule:test']"
          >
            测试
          </el-button>
      </div>
      
      <Table
        :columns="allSchemas.tableColumns"
        :data="tableObject.tableList"
        :loading="loading"
        :pagination="{
          total: tableObject.total
        }"
        v-model:pageSize="tableObject.pageSize"
        v-model:currentPage="tableObject.currentPage"
        ref="TableRef"
        :selection="true"
        @register="register"
        :stripe="true"
        header-cell-class-name="custom-header"
      >
     
      <template #templateName="{ row }">
        <el-button
            link
            type="primary"
          @click="openDetail(row.id)"
          >
          {{ row.templateName }}
          </el-button>
        </template>
      <template #isShare="{ row }">
          <span>{{ row.isShare ==1?'是':'否' }}</span>
        </template>
      <template #produceType="{ row }" v-if="userInfo.divisionCode=='root'">
          <el-switch
            v-model="row.produceType"
            active-value="1"
            inactive-value="0"
            inline-prompt
            :active-icon="Check" :inactive-icon="Close"
            @change="handleStatusChange(row)"
            :disabled="row.dataSourceKey !='root' && row.templateType=='专用' || !checkPermissions(['pictureTemplate:saveOrUpdate'])"
          />
        </template>
        <template #produceType="{ row }" v-else>
          <el-switch
            v-model="row.produceType"
            active-value="1"
            inactive-value="0"
            inline-prompt
            :active-icon="Check" :inactive-icon="Close"
            @change="handleStatusChange(row)"
            :disabled="row.dataSourceKey != userInfo.divisionCode || !checkPermissions(['pictureTemplate:saveOrUpdate'])"
          />
        </template>
        <template #action="{ row }" v-if="userInfo.divisionCode=='root'">
          <div  v-if="row.templateType=='公用'">
            <el-button
            link
            type="primary"
            @click="openForm('update', row.id)"
            v-hasPermi="['pictureTemplate:saveOrUpdate']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(row.id)"
            v-hasPermi="['pictureTemplate:delete']"
          >
            删除
          </el-button>
          </div>
          <div v-if="row.dataSourceKey=='root' && row.templateType=='专用'">
            <el-button
            link
            type="primary"
            @click="openForm('update', row.id)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(row.id)"
          >
            删除
          </el-button>
          </div>
          
          <!-- <el-button
            link
            type="primary"
            @click="openDetail(row.id)"
          >
            详情
          </el-button> -->
          
        </template>
        <template #action="{ row }" v-else>
          <div  v-if="row.dataSourceKey == userInfo.divisionCode">
            <el-button
            link
            type="primary"
            @click="openForm('update', row.id)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(row.id)"
          >
            删除
          </el-button>
          </div>
        </template>
      </Table>
  </div>

  <!-- 表单弹窗：添加/修改 -->
  <ContentWrap v-show="setView==='add'">
    <!-- <ConfigurationForm ref="formRef" @success="getList" @setClose="setClose" /> -->
  </ContentWrap>
  <ContentWrap v-show="setView==='view'">
    <!-- 详情弹窗 -->
    <ConfigurationDetail ref="detailRef" @setClose="setClose" />
  </ContentWrap>
  <TestDrawer ref="TestDrawerRef" />
</template>
<script lang="ts" setup>
 import request from '@/config/axios'
import download from '@/utils/download'
import { allSchemas } from './configuration.data';
import * as imgProduceApi from '@/api/productmange/imgProduce';
import ConfigurationForm from './ConfigurationForm.vue';
import ConfigurationDetail from './ConfigurationDetail.vue';
import TestDrawer from './TestDrawer.vue';
import { templateTypeOpt,userInfo } from '../indexData'
import { Check, Close } from '@element-plus/icons-vue'

defineOptions({ name: 'templateMange' })
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
// tableObject：表格的属性对象，可获得分页大小、条数等属性
// tableMethods：表格的操作对象，可进行获得分页、删除记录等操作
// 详细可见：https://doc.iocoder.cn/vue3/crud-schema/
const { tableObject,register, tableMethods } = useTable(
  {
    getListApi: imgProduceApi.getpictureTemplatePage, // 分页接口
    delListApi: imgProduceApi.deletepictureTemplate, // 删除接口
    defaultParams:{templateName:'',templateType:'',imgSize:'',produceType:''} //传递默认数据
  }
)
// 获得表格的各种操作
const { getList,getSelections, setSearchParams } = tableMethods
const loading = ref(false)
const emit = defineEmits(['setViewFun']) 
const setView = ref('list');
const setViewFun=(type:string)=>{
  setView.value=type;
}
const setClose= async ()=>{
  setView.value='list';
   // 刷新列表
  //  await getList()
  
}
defineExpose({ setClose,getList }) 
const tableData=[
  {
    name:'机器人1',
    webHookUrl:'https://qyapi.weixin.qq.com/cgibin/webhook/send?key=c73daa86-3321-4731-a233-1abfd16f2839',
    isGroup:true,
    status:true
  }
]
/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number|string) => {
  // formRef.value.open(type, id)
  emit('setViewFun',{type, id,str:'templateMangeadd'});
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number|string) => {
  detailRef.value.open(id);
  setViewFun('view');
}

const TableRef = ref() 
const handleSelectionChange = async() => {
    const ids=[]
    const dlis= await getSelections()
    dlis.forEach(item=>{
      console.log('item',item);
      ids.push(item.id)
    })
   
    return ids
}
/** 删除按钮操作 */
const handleDelete = async (id) => {
  //获取选中数据
 const ids =[id] //await handleSelectionChange();
    if(ids.length==0){
        message.info('请选择数据')
        return false
    }
    // 批量删除 获取id数组
    try {
      //确认删除
      await message.delConfirm()
      await imgProduceApi.deletepictureTemplate(ids)
      message.success(t('common.delSuccess'))
      // 刷新列表
      await getList()
    } catch {}
  }
  /** 下载按钮操作 */
const handleDownDoad = async () => {
  //获取选中数据
 const selection = await getSelections();
    if(selection.length==0){
        message.info('请选择数据')
        return false
    }
    const ids = selection.map(item=>item.templateFileId)
    // 批量下载 获取id数组
    try {
      const res =await request.download({ url: `${import.meta.env.VITE_BASE_URL}/admin-api/attachment/downloads?ids=${ids.join(',')}` });
      if(ids.length==1){
        download.smuw(res, selection[0].templateFileName);
      }else{
        download.zip(res, '图件模版.zip')
      }
    } catch {}
  }
const TestDrawerRef = ref()
  /** 测试按钮操作 */
  const handleTest = async () => {
  //获取选中数据
 const ids = await handleSelectionChange();
    if(ids.length==0){
        message.info('请选择数据')
        return false
    }
    // 批量下载 获取id数组
    try {
      TestDrawerRef.value.open(ids)
      // message.success('提交下载数据')

      // await imgProduceApi.deletepictureTemplate(ids)

    } catch {}
  }
/** 修改状态 */
const handleStatusChange = async (row: any) => {
  console.log(row,'000000',row.produceType);
  await imgProduceApi.updatepictureTemplateValid({id:row.id,status:row.produceType})
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
